﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using TouTou.RegexTool;
using Microsoft.VisualBasic;
using System.Timers;

namespace Visual_Studio_Project_Management
{
    public partial class MainForm : Form
    {
        List<string> list = new List<string>();
        List<string> AIlist = new List<string>();

        string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "VSPC");
        string project = null;

        string pathProject = @"C:\Users\" + Environment.UserName + @"\source\repos";
        System.Timers.Timer timer = new System.Timers.Timer();

        public MainForm()
        {
            InitializeComponent();
        }

        private void DebugCommand()
        {
            switch (DebugBox.Text)
            {
                case "debug show SavePanel":
                    Point point = new Point
                    {
                        X = 0,
                        Y = 0
                    };
                    SavePanel.Location = point;
                    SavePanel.Visible = true;
                    break;
                case "debug show allpath":
                    string listtext = "";
                    foreach (string item in list)
                    {
                        listtext += item + Environment.NewLine;
                    }
                    debugmsg.Text = listtext;
                    break;
                case "debug show selectpath":
                    try
                    {
                        int index = listProject.SelectedIndex;
                        debugmsg.Text = list[index];
                    }
                    catch (Exception)
                    {
                        debugmsg.Text = "Please Select The Project To Show The Project Path";
                    }
                    break;
                case "debug timer":
                    debugmsg.Text = timertimenow.ToString();
                    break;
                default:
                    break;
            }
            switch (DebugBox.Text)
            {
                case "debug --version":
                    debugmsg.Text = "--Debug v1.3--";
                    break;
                case "debug --developer":
                    debugmsg.Text = "--JinkerJK";
                    break;
                case "debug --command":
                    string[] command = { "debug show SavePanel", "debug show allpath", "debug show selectpath", "debug timer" };
                    debugmsg.Text = null;

                    for (int i = 0; i < command.Length; i++)
                    {
                        debugmsg.Text += command[i] + Environment.NewLine;
                    }
                    break;
                default:
                    break;
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            string filepath = Path.Combine(path, "VSPC.path");

            if (File.Exists(filepath))
            {
                string[] x = File.ReadAllLines(filepath);
                pathProject = x[0];
            }
            if (!Directory.Exists(pathProject))
            {
                MessageBox.Show("No Found Visual Studio Project.You can edit path on", "Find error:");
                Point point = new Point
                {
                    X = 0,
                    Y = 0
                };
                SavePanel.Location = point;
                SavePanel.Visible = true;
            }
            RefreshNow();
            timer.Interval = 3000;
            timer.Elapsed += DebugMsgReset;
            timer.AutoReset = false;
        }
        int timertimenow = 0;
        private void DebugMsgReset(object sender, ElapsedEventArgs e)
        {
            debugmsg.Text = "I am JinkerJK.I want to be a programmer!";
            timertimenow++;
        }

        private void ClearAllBtn_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < listProject.Items.Count; i++)
            {
                DeleteFolder(list[i]);
            }
            RefreshNow();
            MessageBox.Show("Finish!","VSProject_Clear:");
        }

        /// <summary>
        /// 删除文件夹（及文件夹下所有子文件夹和文件）
        /// </summary>
        /// <param name="directoryPath"></param>
        public static void DeleteFolder(string directoryPath)
        {
            foreach (string d in Directory.GetFileSystemEntries(directoryPath))
            {
                if (File.Exists(d))
                {
                    FileInfo fi = new FileInfo(d);
                    if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                        fi.Attributes = FileAttributes.Normal;
                    File.Delete(d);     //删除文件   
                }
                else
                    DeleteFolder(d);    //删除文件夹
            }
            Directory.Delete(directoryPath);    //删除空文件夹
        }

        public void RefreshNow()
        {
            list.Clear();
            listProject.Items.Clear();
            list.AddRange(Directory.GetDirectories(pathProject));
            DirectoryInfo directoryInfo;
            foreach (string item in list)
            {
                directoryInfo = new DirectoryInfo(item);
                listProject.Items.Add(directoryInfo.Name);
            }
        }

        private void ClearSelectedBtn_Click(object sender, EventArgs e)
        {
            try
            {
                int index = listProject.SelectedIndex;
                DeleteFolder(list[index]);
                listProject.Items.RemoveAt(index);
                RefreshNow();
                MessageBox.Show("Finish!", "VSProject_Clear:");
            }
            catch (Exception)
            {
                MessageBox.Show("Please Selected!","error");
            }
        }

        private void refreshBtn_Click(object sender, EventArgs e)
        {
            listProject.Items.Clear();
            RefreshNow();
        }

        private void AIRefresh_Click(object sender, EventArgs e)
        {
            TouTouRegex touTouRegex = new TouTouRegex();
            RefreshNow();
            AIlist.Clear();
            string[] name = { "ClassLibrary", "WindowsFormsApp", "WpfApp", "ConsoleApp" };
            DirectoryInfo directoryInfo;
            foreach (string item in list)
            {
                if (touTouRegex.CheckContainsByReg(item, name))
                {
                    AIlist.Add(item);
                }
            }
            listProject.Items.Clear();
            foreach (string item in AIlist)
            {
                directoryInfo = new DirectoryInfo(item);
                listProject.Items.Add(directoryInfo.Name);
            }
            list.Clear();
            list.AddRange(AIlist);
        }

        private void SavePath_Click(object sender, EventArgs e)
        {
            string filepath = Path.Combine(path, "VSPC.path");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            if (!File.Exists(filepath))
            {
                FileStream fs = new FileStream(filepath, FileMode.Create, FileAccess.ReadWrite);
                fs.Close();
            }
            List<string> listpath = new List<string>();
            listpath.Add(CustomPath.Text);
            File.WriteAllLines(filepath, listpath);
        }

        private void DebugBtn_Click(object sender, EventArgs e)
        {
            DebugCommand();
            
        }

        private void label1_Click(object sender, EventArgs e)
        {
            switch (DebugBox.Visible)
            {
                case true:
                    DebugBtn.Visible = true;
                    break;
                case false:
                    DebugBox.Visible = true;
                    break;
                default:
                    break;
            }
        }

        private void SelectProjectBtn_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.Description = "Select Your Visual Studio Project";
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                project = folderBrowserDialog.SelectedPath;
                importbox.Text = folderBrowserDialog.SelectedPath;
            }

        }

        private void ImportBtn_Click(object sender, EventArgs e)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(project);
            string xpath = Path.Combine(pathProject, directoryInfo.Name);
            if (Directory.Exists(xpath))
            {
                debugmsg.Text = "This project already exists.";
                timer.Enabled = true;
                return;
            }
            Directory.CreateDirectory(xpath);
            Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(project, xpath);
            debugmsg.Text = "Import Finish!";
            timer.Enabled = true;
            RefreshNow();
        }

        private void DebugBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                DebugBtn.PerformClick();
            }
        }
    }
}
